<script setup lang="ts">
import type { FormSchemaGetter } from '#/adapter/form';

import { computed, h, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';
import { cloneDeep, getPopupContainer } from '@vben/utils';
import { Button, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { eventAdd, eventGetById, eventUpdate } from '#/api/dataCollect/event';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{ reload: [] }>();
async function addSeparator() {
  // getDictOptions(DictEnum.DATA_EVENT_TYPE)
  const data = cloneDeep(await formApi.getValues());
  if (!data.keywords) {
    message.warning('输入不能为空！');
    return;
  }
  data.keywords = `${data.keywords}、`;
  formApi.setValues(data);
}
async function setupSecondlSelect(value: any) {
  let options = null;
  if (value === '台海-军事') {
    options = getDictOptions(DictEnum.DATA_EVENT_JUNSHI);
  } else if (value === '台海-政治') {
    options = getDictOptions(DictEnum.DATA_EVENT_ZHENGZHI);
  } else {
    options = getDictOptions(DictEnum.DATA_EVENT_JINGJI);
  }
  // getDictOptions(DictEnum.DATA_EVENT_TYPE)
  formApi.updateSchema([
    {
      component: 'Select',
      componentProps: {
        style: { width: '434px' },
        allowClear: false,
        options,
        getPopupContainer,
        // 选项变化时触发
        onChange: async (value: string) => {
          // const data = await formApi.getValues();
          // setupTableSelect(value, data.apiKey);
          // formApi.setFieldValue('resourceId', undefined);
        },
      },
      defaultValue: '',
      fieldName: 'eventSecondLevel',
      label: '子事件类型',
      rules: 'required',
    },
  ]);
}
const modalSchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
  },
  {
    component: 'Select',
    componentProps: {
      style: { width: '434px' },
      allowClear: false,
      options: getDictOptions(DictEnum.DATA_EVENT_TYPE),
      getPopupContainer,
      // 选项变化时触发
      onChange: async (value: string) => {
        setupSecondlSelect(value);
        formApi.setFieldValue('eventSecondLevel', undefined);
      },
    },
    defaultValue: '',
    fieldName: 'eventFirstLevel',
    label: '事件类型',
    rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      style: { width: '434px' },
      allowClear: false,
      options: [],
      getPopupContainer,
      // 选项变化时触发
      onChange: async (value: string) => {
        // const data = await formApi.getValues();
        // setupTableSelect(value, data.apiKey);
        // formApi.setFieldValue('resourceId', undefined);
      },
    },
    defaultValue: '',
    fieldName: 'eventSecondLevel',
    label: '子事件类型',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'keywords',
    label: '关键字',
    componentProps: {
      suffix: h(Button, { onClick: addSeparator }, '添加分隔符'),
    },
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      options: getDictOptions(DictEnum.SYS_NORMAL_DISABLE),
      optionType: 'button',
    },
    defaultValue: '0',
    fieldName: 'status',
    formItemClass: 'col-span-2 lg:col-span-1',
    label: '状态',
  },
];

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 80,
  },
  schema: modalSchema(),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await eventGetById(id);
      await formApi.setValues(record);
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? eventUpdate(data) : eventAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="h-[450px] w-[550px]">
    <BasicForm>
      <!-- <template #toolbar>
        <Button type="default" @click="handleCustomBtn">自定义按钮</Button>
      </template> -->
    </BasicForm>
  </BasicModal>
</template>
